package flowcontrol.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：演示Condition的基本用法
 */

public class ConditionDemo01 {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition(); // condition对象是通过lock对象创建的

    void method1() {
        try {
            lock.lock();
            System.out.println("当前线程：" + Thread.currentThread().getName() + "进入等待状态...");
            condition.await(); // 当前线程进入等待状态
            System.out.println("当前线程：" + Thread.currentThread().getName() + "被唤醒...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    void method2() {
        try {
            lock.lock();
            System.out.println("当前线程：" + Thread.currentThread().getName() + "进入...");
            Thread.sleep(3000);
            condition.signal(); // 唤醒在condition上等待的线程
            System.out.println("当前线程：" + Thread.currentThread().getName() + "发出唤醒...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ConditionDemo01 demo = new ConditionDemo01();
        new Thread(demo::method1, "t1").start();
        Thread.sleep(1000);
        new Thread(demo::method2, "t2").start();
    }
}
